<template>
  <div class="explore-page full-bleed">
    <div class="explore-themed full">
      <header class="explore-header-bar">
        <div>
          <h1 class="explore-title">探索模式</h1>
          <p class="explore-sub">按节点/任务结构进行引导式学习与探索</p>
        </div>
        <div class="badge-level" v-if="summary">
          <span class="dot"></span>
          <span>Lv. {{ summary.level }}</span>
          <span>· EXP {{ summary.exp_total }}</span>
          <span>· 已完成 {{ summary.quests_done }}</span>
        </div>
        <el-alert v-else type="info" :closable="false" title="未登录，进度将不会关联账号" class="mb-8" />
        <div class="toolbar">
          <el-button size="small" @click="$router.push('/explore/achievements')">成就</el-button>
          <el-button size="small" @click="$router.push('/explore/graph')">图谱</el-button>
          <el-button size="small" @click="rulesVisible = true">节点与任务</el-button>
        </div>
      </header>

      <section class="filters-bar">
        <el-select v-model="filters.level" placeholder="难度等级" clearable @change="loadNodes">
        <el-option v-for="l in [1,2,3,4,5]" :key="l" :label="'Lv.'+l" :value="l" />
        </el-select>
        <el-input v-model="filters.category" placeholder="分类（可选）" clearable @change="loadNodes" style="max-width:200px" />
      </section>

      <section class="node-list">
        <el-empty description="暂无节点" v-if="!loading && nodes.length === 0" />
        <el-row :gutter="16">
          <el-col v-for="n in nodes" :key="n.id" :xs="24" :sm="12" :md="8" :lg="6">
            <el-card
              class="node-card modern-vintage"
              shadow="hover"
              :class="{ locked: n.is_locked }"
              @click="onCardClick(n)"
              :title="n.is_locked ? (n.locked_reason || '节点未解锁') : ''"
            >
              <div class="title">{{ n.title }}</div>
              <div class="desc">{{ n.short_desc }}</div>
              <div class="meta">
                <el-tag size="small">Lv. {{ n.level }}</el-tag>
                <el-tag size="small" type="info" v-if="n.category">{{ n.category }}</el-tag>
                <el-tag v-if="n.is_locked" size="small" type="warning">未解锁</el-tag>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </section>
    </div>
  </div>
  <el-dialog v-model="rulesVisible" title="探索模式 · 节点与任务规则" width="640px">
    <div class="rules">
      <h4>核心概念</h4>
      <ul>
        <li>节点：一个主题单元（含简介、AI 解读、任务等）。</li>
        <li>任务：完成节点目标的微行动，获得经验 EXP 与成就积分。</li>
      </ul>
      <h4>任务类型</h4>
      <ul>
        <li><b>READ</b>：阅读计时，达到要求秒数后可完成（自动上报进度）。</li>
        <li><b>VISIT</b>：已阅确认，点击“已阅确认”记录 visited 后可完成。</li>
        <li><b>COLLECT</b>：收集计数，点击“收集 +1”累计到目标数量后可完成。</li>
        <li><b>MATCH</b>：配对，把左侧词条与右侧释义两两对应，全部正确后可完成。</li>
        <li><b>ORDER</b>：排序，使用“上移/下移”调整卡片位置，恢复正确顺序即可完成。</li>
      </ul>
      <h4>解锁与等级</h4>
      <ul>
        <li>节点可能有解锁前置（由图谱连线定义，多个前置默认为 AND）。</li>
        <li>难度等级（Lv.）是硬门槛：等级未达即便默认解锁也不可操作。</li>
      </ul>
      <h4>进度与成就</h4>
      <ul>
        <li>进度会在服务端回显（progress_json），页面刷新不丢失。</li>
        <li>成就会在完成任务或进入成就页时自动判定并授予。</li>
      </ul>
      <p class="tip">提示：写操作（开始/进度/完成）需登录；未解锁的节点将禁用相关按钮。</p>
    </div>
    <template #footer>
      <el-button @click="rulesVisible=false">知道了</el-button>
    </template>
  </el-dialog>
  
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { exploreApi } from '@/api/explore'
import { getToken } from '@/utils/auth'
import { ElMessage } from 'element-plus'

const nodes = ref([])
const summary = ref(null)
const loading = ref(false)
const filters = reactive({ level: undefined, category: '' })
const router = useRouter()
const rulesVisible = ref(false)

const loadSummary = async () => {
  try {
    const token = getToken()
    console.log('🔍 探索模式 - Token状态:', token ? `存在 (${token.substring(0, 20)}...)` : '不存在')
    
    const { data } = await exploreApi.userSummary()
    console.log('📊 探索模式 - 用户摘要数据:', data)
    summary.value = data
  } catch (err) {
    console.error('❌ 探索模式 - 加载摘要失败:', err)
    console.error('错误详情:', err.response?.data)
    // 未登录/401 即保持空
    summary.value = null
  }
}

const loadNodes = async () => {
  loading.value = true
  try {
    const params = {}
    if (filters.level) params.level = filters.level
    if (filters.category) params.category = filters.category
    const { data } = await exploreApi.listNodes(params)
    nodes.value = data
  } finally { loading.value = false }
}

onMounted(() => { if (getToken()) loadSummary(); loadNodes() })

function onCardClick(n) {
  if (n.is_locked) {
    const reason = n.locked_reason || '节点未解锁'
    ElMessage.warning(reason)
    return
  }
  router.push(`/explore/node/${n.id}`)
}
</script>

<style scoped>
.explore-page { padding: 8px 0; }
.explore-header { display:flex; align-items:center; gap:12px; flex-wrap:wrap; margin-bottom:10px; }
.explore-header h1 { margin:0; font-size:22px; }
.explore-header .sub { margin:0; color:#666; }
.explore-header .nav-links { margin-left:auto; display:flex; gap:8px; }
.filters { display:flex; gap:10px; margin:12px 0 16px; }
.node-card { cursor:pointer; margin-bottom:14px; }
.node-card.locked { filter: grayscale(0.6); opacity: 0.7; cursor: not-allowed; }
.node-card .title { font-weight:600; margin-bottom:6px; }
.node-card .desc { color:#666; font-size:13px; min-height: 38px; }
.node-card .meta { display:flex; gap:6px; margin-top:8px; }
.rules .tip { color:#666; }
</style>
